﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using ThresholdAssistant.ConfigSdk.Constants;
using System;
using System.IO;

namespace ThresholdAssistant.ConfigSdk
{
    /// <summary>
    /// 本地订阅JSON配置文件
    /// </summary>
    public static class SubscribeJson
    {
        /// <summary>
        /// 文件路径（默认：Config）
        /// </summary>
        public static string FileDir = null;

        /// <summary>
        /// 文件名称
        /// </summary>
        public static string FileName = "subscribe.json";

        /// <summary>
        /// 配置文件信息
        /// </summary>
        public static IConfiguration Configuration { get; set; }

        /// <summary>
        /// 使用独立的JSON配置文件
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="fileDir"></param>
        /// <returns></returns>
        public static IHostBuilder UseSubscribeJson(this IHostBuilder builder, string fileDir = null)
        {
            var environmentVariable = EnvConstant.GetEnv();//环境变量值
            if (!string.IsNullOrEmpty(environmentVariable))
            {
                //设置环境变量
                builder.UseEnvironment(environmentVariable);
            }

            var fileName = "subscribe";
            if (!string.IsNullOrEmpty(environmentVariable))
            {
                fileName += $".{environmentVariable}";
            }

            var projectVariable = EnvConstant.GetProject();//项目名称
            if (!string.IsNullOrEmpty(projectVariable))
            {
                fileName += $".{projectVariable}";
            }
            SetJsonConfiguration(fileDir, $"{fileName}.json");
            return builder;
        }

        /// <summary>
        /// 获取配置信息
        /// </summary>
        /// <param name="fileDir"></param>
        /// <param name="fileName">文件名称</param>
        /// <returns></returns>
        private static void SetJsonConfiguration(string fileDir, string fileName)
        {
            if (string.IsNullOrEmpty(fileDir))
            {
                //默认读取根目录配置
                fileDir = Path.Combine(AppContext.BaseDirectory, "Config");
            }
            FileDir = fileDir;
            FileName = fileName;
            Configuration = ComJsonConf.GetJsonConfiguration(fileDir, fileName);
        }
    }
}